import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:flutter_demo/pages/page_with_title.dart';
import 'package:flutter_demo/widgets/app_widgets.dart';

import '../../../conf/m3.dart';

class GestureDetectorPage extends PageWithTitle {
  GestureDetectorPage()
      : super("手势检测(GestureDetector)", key: GlobalKey<PageWithTitleState>());

  @override
  List<Widget> buildContentWidgets(BuildContext context) {
    return [
      const PrimaryTitle("简介"),
      const BodyText("Flutter基于触摸事件也提供了手势检测，便于开发者快速开发功能"),
      AppSpacer.large,
      _Example(key as GlobalKey<PageWithTitleState>),
      AppSpacer.mini,
      const UlItem("GestureDetector"),
      const BodyText("手势检测，可以快速实现点击、双击、长按、拖动、缩放等手势监听，实现功能，"
          "其中点击长按貌似还支持双指和三指监听"),
      const LabelText("- onTap 单击事件，若无特殊需要则使用这个回调来实现即可"),
      const LabelText("  - onTapDown 单击按下"),
      const LabelText("  - onTapUp 单击抬起"),
      const LabelText("  - onTapCancel 单击取消"),
      const LabelText("- onSecondaryTap onTertiaryTap，双指单击、三指单击"),
      const LabelText("- onDoubleTap 双击事件"),
      const LabelText("  - onDoubleTapDown 双击按下"),
      const LabelText("  - onDoubleTapCancel 双击取消"),
      const LabelText("- onLongPress 长按事件"),
      const LabelText("  - onLongPressStart 长按开始"),
      const LabelText("  - onLongPressMoveUpdate 长按过程中移动"),
      const LabelText("  - onLongPressUp 长按抬起"),
      const LabelText("  - onLongPressEnd 长按结束（不包含抬起时的位置信息）"),
      const LabelText("- onSecondaryLongPress onTertiaryLongPress，双指长按、三指长按"),
      const LabelText("拖动，监听事件挺多，分水平和垂直方向的事件进行处理"),
      const LabelText("  - onVerticalDragDown 垂直拖拽按下（在触发长按的时间判定内移动一段距离即可触发开始拖拽）"),
      const LabelText("  - onVerticalDragStart 垂直拖拽开始"),
      const LabelText("  - onVerticalDragUpdate 垂直拖拽中"),
      const LabelText("  - onVerticalDragEnd 垂直拖拽结束"),
      const LabelText("  - onVerticalDragCancel 垂直拖拽取消"),
      const LabelText("ForcePress 带压感的屏幕（iphone）可以监听到压力变化"),
      const LabelText("Pan 触摸板（笔记本）事件"),
      const LabelText("缩放事件"),
      const LabelText("  - onScaleStart 开始缩放"),
      const LabelText("  - onScaleUpdate 缩放更新，可以获取到相对于开始时的缩放比例变化，也提供单独的横向、纵向缩放比例"),
      const LabelText("  - onScaleEnd 结束缩放"),
    ];
  }
}

class _Example extends StatelessWidget {
  final GlobalKey<PageWithTitleState> pageKey;
  static final pointersColor = [
    Colors.blue,
    Colors.green,
    Colors.red,
    Colors.deepOrange,
    Colors.brown,
    Colors.amber,
    Colors.greenAccent,
    Colors.black,
    Colors.deepPurple,
    Colors.pinkAccent,
  ];

  static const pointRadius = 24;
  static final LinkedHashMap<int, Offset> pointersPosition = LinkedHashMap();
  String latestEvent = "";

  _Example(this.pageKey);

  @override
  Widget build(BuildContext context) {
    return StatefulBuilder(
      builder: (context, setState) {
        List<Widget> pointerWidgets = [];
        for (final (index, position) in pointersPosition.values.indexed) {
          pointerWidgets.add(Positioned(
            left: position.dx - pointRadius,
            top: position.dy - pointRadius,
            width: pointRadius * 2,
            height: pointRadius * 2,
            child: DecoratedBox(
              decoration: BoxDecoration(
                  color: pointersColor[index], shape: BoxShape.circle),
            ),
          ));
        }
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(latestEvent),
            GestureDetector(
              onTap: () {
                setState(() => latestEvent = "点击");
              },
              onTapDown: (tapDownDetails) {
                setState(() {
                  pointersPosition[0] = tapDownDetails.localPosition;
                });
              },
              onTapUp: (tapUpDetails) {
                setState(() {
                  pointersPosition.remove(0);
                });
              },
              onTapCancel: () {
                setState(() {
                  pointersPosition.remove(0);
                });
              },
              onDoubleTap: () {
                setState(() => latestEvent = "双击");
              },
              onLongPress: () {
                setState(() => latestEvent = "长按");
              },
              onHorizontalDragDown: (dragDownDetails) {},
              onHorizontalDragStart: (dragStartDetails) {
                setState(() {
                  latestEvent =
                      "横向拖拽(${dragStartDetails.localPosition.dx.toInt()},${dragStartDetails.localPosition.dy.toInt()})";
                  pointersPosition[0] = dragStartDetails.localPosition;
                });
              },
              onHorizontalDragUpdate: (dragUpdateDetails) {
                setState(() {
                  latestEvent =
                      "横向拖拽(${dragUpdateDetails.localPosition.dx.toInt()},${dragUpdateDetails.localPosition.dy.toInt()})";
                  pointersPosition[0] = dragUpdateDetails.localPosition;
                });
              },
              onHorizontalDragEnd: (dragEndDetails) {
                setState(() {
                  latestEvent = "";
                  pointersPosition.remove(0);
                });
              },
              onHorizontalDragCancel: () {
                setState(() {
                  latestEvent = "";
                });
              },
              onScaleStart: (scaleStartDetails) {
                setState(() {
                  latestEvent = "开始缩放";
                });
              },
              onScaleUpdate:  (scaleUpdateDetails) {
                setState(() {
                  latestEvent = "缩放中(${scaleUpdateDetails.scale})";
                });
              },
              onScaleEnd:(scaleEndDetails) {
                setState(() {
                  latestEvent = "结束缩放";
                });
              },
              child: AspectRatio(
                aspectRatio: 1,
                child: DecoratedBox(
                  decoration: BoxDecoration(
                    color: Theme.of(context).colorScheme.surfaceContainer,
                    borderRadius: M3.connerRadiusMedium,
                  ),
                  child: Stack(
                    children: pointerWidgets,
                  ),
                ),
              ),
            )
          ],
        );
      },
    );
  }
}
